# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import typing as t

from ksai.persistence.storage.attachment import Attachment
from ksai.serializer import JsonSerializable


class DocumentSection(JsonSerializable):
    title: t.Optional[str]
    text: t.Optional[str]
    page: t.Optional[int] = 1

    def __init__(self,
                 title: t.Optional[str] = None,
                 text: t.Optional[str] = None,
                 page: t.Optional[int] = 1):
        self.title = title
        self.text = text
        self.page = page

    @staticmethod
    def from_dict(d: dict):
        return DocumentSection(
            title=d.get('title'),
            text=d.get('text'),
            page=int(d.get('page'))
        )

    def serialize(self) -> t.Optional[dict]:
        return {
            'title': self.title,
            'text': self.text,
            'page': self.page,
        }


class Document(JsonSerializable):
    attachment: t.Optional[Attachment]
    sections: t.Optional[t.List[DocumentSection]]

    def __init__(self,
                 attachment: t.Optional[Attachment] = None,
                 sections: t.Optional[t.List[DocumentSection]] = None):
        self.attachment = attachment
        self.sections = sections

    def add_section(self, section: t.Optional[DocumentSection]) -> 'Document':
        if self.sections is None:
            self.sections = []
        if section is not None:
            self.sections.append(section)
        return self

    def has_sections(self):
        return len(self.sections) > 0

    def serialize(self) -> t.Optional[dict]:
        return {
            'attachment': self.attachment,
            'sections': self.sections,
        }


class DocumentException(Exception):
    pass
